import { _decorator, assetManager, Component, ImageAsset, instantiate, Node, Prefab, resources, Sprite, SpriteFrame, Texture2D } from 'cc';
import { UIManager } from './UIManager';
import { GameData } from './GameData';
import { PREVIEW } from 'cc/env';
const { ccclass, property } = _decorator;

@ccclass('Util')
export class Util {

    /**加载动态图片资源 */
    public static loadSprite(url:string, sp:Sprite){
        // 加载 SpriteFrame，image 是 ImageAsset，spriteFrame 是 image/spriteFrame，texture 是 image/texture  "test_assets/image/spriteFrame"
        resources.load(url + "/spriteFrame", SpriteFrame, (err, spriteFrame) => {
            if (err){
                console.log("图标加载失败" + url)
                return;
            }
            sp.spriteFrame = spriteFrame;
        });
    }

    /**远程加载动态图片资源 */
    public static loadRemoteUrl(remoteUrl:string, sp:Sprite){
        if (remoteUrl == "" || remoteUrl == " "){
            return;
        }
        assetManager.loadRemote<ImageAsset>(remoteUrl, function (err, imageAsset) {
            if (err){
                console.log("远程图标加载失败" + remoteUrl)
                return;
            }
            const texture = new Texture2D();
            texture.image = imageAsset;
            sp.spriteFrame.texture = texture;
        });
    }


    /**加载动态预制体资源 */
    public static loadPrefab(url:string, content:Node){
        resources.load(url, Prefab, (err, prefab) => {
            const newNode = instantiate(prefab);
            content.addChild(newNode);
        });
    }

    /**分享游戏 */
    public static shareGame(){
        UIManager.showTip("分享功能待接入")
    }

    /**是否有足够的钱 */
    public static isEnoughCoin(cost:number, isShowTip:boolean = true){
        if (GameData.getIns().userData.coin >= cost){
            return true;
        }

        if (isShowTip){
            UIManager.showTip("金币不足")
        }

        return false;
    }

    /**是否测试版 */
    public static isTest(){
        if(PREVIEW){
            return true;
        }
        return false;
    }

}